import store from '../'
import config from '../../configs'
import util from '../../utils'
import { Message } from "iview"
import { Drafty } from "tinode-sdk"
export function formatMsg(msg) {
    const nim = store.state.nim
    if (msg.type === 'robot') {
        if (msg.content && msg.content.flag === 'bot') {
            if (msg.content.message) {
                msg.content.message = msg.content.message.map(item => {
                    switch (item.type) {
                        case 'template':
                            item.content = nim.parseRobotTemplate(item.content)
                            break
                        case 'text':
                        case 'image':
                        case 'answer':
                            break
                    }
                    return item
                })
            }
        }
    }
    return msg
}

export function onRoamingMsgs(obj) {
    let msgs = obj.msgs.map(msg => {
        return formatMsg(msg)
    })
    store.commit('updateMsgs', msgs)
}

export function onOfflineMsgs(obj) {
    let msgs = obj.msgs.map(msg => {
        return formatMsg(msg)
    })
    store.commit('updateMsgs', msgs)
}

export function onMsg(msg) {
    msg = formatMsg(msg)
    console.log('onMsg', msg)
    store.commit('putMsg', msg)
    if (msg.topic === store.state.currSessionId) {
        store.commit('updateCurrSessionMsgs', {
            type: 'put',
            msg
        })
        // 发送已读回执
        store.dispatch('sendMsgReceipt')
    }
    if (msg.scene === 'team' && msg.type === 'notification') {
        store.dispatch('onTeamNotificationMsg', msg)
    }
}

function onSendMsgDone(error, msg) {
    store.dispatch('hideLoading')
    if (error) {
        // 被拉黑
        // console.log(error)
        if (error.code === 7101) {
            msg.status = 'success'
            Message.success(error.message)
        } else {
            Message.error(error.message)
        }
    }
    onMsg(msg)
}

// 消息撤回
export function onRevocateMsg(error, msg) {
    const nim = store.state.nim
    if (error) {
        if (error.code === 508) {
            Message.error('发送时间超过2分钟的消息，不能被撤回')
        } else {
            Message.error(error)
        }
        return
    }
    let tip = ''
    if (msg.from === store.state.userUID) {
        tip = '你撤回了一条消息'
    } else {
        let userInfo = store.state.userInfos[msg.from]
        if (userInfo) {
            tip = `${util.getFriendAlias(userInfo)}撤回了一条消息`
        } else {
            tip = '对方撤回了一条消息'
        }
    }
    nim.sendTipMsg({
        isLocal: true,
        scene: msg.scene,
        to: msg.to,
        tip,
        time: msg.time,
        done: function sendTipMsgDone(error, tipMsg) {
            console.log(error)
            let idClient = msg.deletedIdClient || msg.idClient
            store.commit('replaceMsg', {
                sessionId: msg.sessionId,
                idClient,
                msg: tipMsg
            })
            if (msg.sessionId === store.state.currSessionId) {
                store.commit('updateCurrSessionMsgs', {
                    type: 'replace',
                    idClient,
                    msg: tipMsg
                })
            }
        }
    })
}


export function revocateMsg({ state, commit }, msg) {
    console.log(commit)
    const nim = state.nim
    let { idClient } = msg
    msg = Object.assign(msg, state.msgsMap[idClient])
    nim.deleteMsg({
        msg,
        done: function deleteMsgDone(error) {
            onRevocateMsg(error, msg)
        }
    })
}
export function updateLocalMsg({ state, commit }, msg) {
    console.log(commit)
    store.commit('updateCurrSessionMsgs', {
        type: 'replace',
        idClient: msg.idClient,
        msg: msg
    })
    state.nim.updateLocalMsg({
        idClient: msg.idClient,
        localCustom: msg.localCustom
    })
    store.commit('replaceMsg', {
        sessionId: msg.sessionId,
        idClient: msg.idClient,
        msg: msg
    })
}

// 发送普通消息
export function sendMsg({ state, commit }, obj) {
    console.log(commit)
    const nim = state.nim
    obj = obj || {}
    let type = obj.type || ''
    store.dispatch('showLoading')
    const topic = nim.getTopic(state.currSessionId)
    let msg = topic.createMessage(obj.text, false)
    if (!topic.isSubscribed()) {
        topic.subscribe();
        topic.subscriber(state.currSessionId)
    }
    console.log(msg)
    switch (type) {
        case 'text':
            console.log(topic.isSubscribed())
            topic.publishDraft(msg, null)
                .then((ctrl) => {
                    console.log(ctrl)
                    topic.messages(m => {
                        if (m.id && m.id === ctrl.id) {
                            onMsg(m)
                        }
                    })
                })
                .catch((err) => {
                    console.log('err--->' + err.message);
                })
            // nim.sendText({
            //     scene: obj.scene,
            //     // custom:'{}',
            //     to: obj.to,
            //     text: obj.text,
            //     done: onSendMsgDone,
            //     needMsgReceipt: obj.needMsgReceipt || false
            // })
            break
        case 'custom':
            nim.sendCustomMsg({
                scene: obj.scene,
                to: obj.to,
                pushContent: obj.pushContent,
                content: JSON.stringify(obj.content),
                done: onSendMsgDone
            })
    }
}

// 发送文件消息
export function sendFileMsg({ state, commit }, obj) {
    console.log(commit)
    const nim = state.nim
    let { type, fileInput } = obj
    if (!type && fileInput) {
        type = 'file'
        if (/\.(png|jpg|bmp|jpeg|gif)$/i.test(fileInput.value)) {
            type = 'image'
        } else if (/\.(mov|mp4|ogg|webm)$/i.test(fileInput.value)) {
            type = 'video'
        }
    }
    console.log(obj)
    store.dispatch('showLoading')
    // console.log(nim)
    let uploader = nim.getLargeFileHelper();
    // const uploadCompletionPromise = uploader.upload(fileInput, function (prs) {
    //     console.log(prs)
    // }, function (res) {
    //     console.log(res)
    // }, function (err) {
    //     Message.error(err.code+' '+err.text)
    //     console.log(err)
    // });
    let baseUrl = 'http://192.168.31.67:6060/v0/file'
    const uploadCompletionPromise = uploader.uploadWithBaseUrl(baseUrl,fileInput, function (prs) {
        console.log(prs)
    }, function (res) {
        console.log(res)
    }, function (err) {
        Message.error(err.code+' '+err.text)
        console.log(err)
    });

    const msg = Drafty.attachFile(null, fileInput.type, null, fileInput.name, fileInput.size, uploadCompletionPromise);
    // this.props.sendMessage(msg, uploadCompletionPromise, uploader);
    console.log(msg)
    // const data = Object.assign({
    //     type,
    //     uploadprogress: function (data) {
    //         console.log(data.percentageText)
    //     },
    //     uploaderror: function () {
    //         fileInput.value = ''
    //         console && console.log('上传失败')
    //     },
    //     uploaddone: function (error, file) {
    //         fileInput.value = ''
    //         console.log(error);
    //         console.log(file);
    //     },
    //     beforesend: function (msg) {
    //         console && console.log('正在发送消息, id=', msg);
    //     },
    //     done: function (error, msg) {
    //         onSendMsgDone(error, msg)
    //     }
    // }, obj)
    // nim.sendFile(data)
}

// 发送机器人消息
export function sendRobotMsg({ state, commit }, obj) {
    console.log(commit)
    const nim = state.nim
    let { type, scene, to, robotAccid, content, params, target, body } = obj
    scene = scene || 'p2p'
    if (type === 'text') {
        nim.sendRobotMsg({
            scene,
            to,
            robotAccid: robotAccid || to,
            content: {
                type: 'text',
                content,
            },
            body,
            done: onSendMsgDone
        })
    } else if (type === 'welcome') {
        nim.sendRobotMsg({
            scene,
            to,
            robotAccid: robotAccid || to,
            content: {
                type: 'welcome',
            },
            body,
            done: onSendMsgDone
        })
    } else if (type === 'link') {
        nim.sendRobotMsg({
            scene,
            to,
            robotAccid: robotAccid || to,
            content: {
                type: 'link',
                params,
                target
            },
            body,
            done: onSendMsgDone
        })
    }
}

// 发送消息已读回执
export function sendMsgReceipt({ state, commit }) {
    console.log(commit)
    // 如果有当前会话
    let currSessionId = store.state.currSessionId
    if (currSessionId) {
        // 只有点对点消息才发已读回执 /^p2p-/.test(currSessionId)
        // console.log(util.parseSession(currSessionId))
        const topic = state.nim.getTopic(currSessionId);
        if (!topic) {
            return
        }
        if (topic.getType() === 'grp') {
            console.log('群聊天')
        }
        if (topic.getType() === 'p2p') {
            console.log('单聊')
        }
        // if (/^usr/.test(currSessionId)) {
        //     let msgs = store.state.currSessionId
        //     console.log(msgs)
        //     const nim = state.nim
        //     console.log(state.sessionMap[currSessionId])
        //     if (state.sessionMap[currSessionId]) {
        //         console.log(1111)
        //         const topic = nim.getTopic(currSessionId);
        //         topic.noteRecv(state.sessionMap[currSessionId].seq);
        //         if (topic && topic.isSubscribed() && topic.msgHasMoreMessages()) {
        //             topic.getMessagesPage(config.localMsglimit).catch((err) => {
        //                 console.log(err)
        //                 // this.setState({ fetchingMessages: false });
        //                 // this.props.onError(err.message, 'err');
        //             });
        //         }
        //         // getHistoryMsgs({ state, commit }, obj)
        //         // nim.msgReceiptCount({
        //         //     // msg: state.sessionMap[currSessionId].lastMsg,
        //         //     // done: function sendMsgReceiptDone(error, obj) {
        //         //     //     // do something
        //         //     //     // console.log(error,obj)
        //         //     //     console.log('发送消息已读回执' + (!error ? '成功' : '失败'), error, obj);
        //         //     //     // getHistoryMsgs({ state, commit }, obj)
        //         //     // }
        //         //     // function sendMsgReceiptDone(error, obj) {
        //         //     //     // do something
        //         //     //     // console.log(error,obj)
        //         //     //     sendMsgReceiptDone(error, obj)
        //         //     // }
        //         // })
        //     }
        // }
    }
}

// function sendMsgReceiptDone(error, obj) {
//     console.log('发送消息已读回执' + (!error ? '成功' : '失败'), error, obj);
// }

// 获取云端消息
export function getHistoryMsgs({ state, commit }, obj) {
    console.log(obj, state.currSessionId)
    console.log(commit)
    const nim = state.nim
    // console.log(nim)
    const topic = nim.getTopic(obj.sessionId);
    console.log(topic.isSubscribed())
    // if (!topic.isSubscribed()) {
    //     topic.subscribe();
    // }
    // console.log('319---->', topic)
    // console.log('getType---->', topic.getType())
    // console.log(topic.isSubscribed() && topic.msgHasMoreMessages())
    // let msgs = [];
    // console.log(topic.msgHasMoreMessages())

    let msgMews = false;
    // if (state.currSessionMsgs.length > 0) {
    //     msgMews = false
    // } else {s
    //     msgMews = true
    // }
    topic.getMessagesPage(config.localMsglimit, msgMews).catch((err) => {
        console.log('358--err-->', err.message)
        // Message.error(err.message)
        console.log(err)
        if (err.message === "Timeout (504)") {
            Message.error('请求超时,请检查网络后重试')
        }
        if (err.message === "permission denied (403)" && topic.getType() === "grp") {
            Message.error('您已经被移出群聊')
        }
    })
    // alert(state.beforeId, 'state.beforeId')
    // topic.messages(null, 1, state.beforeId)
    // if (state.currSessionId && state.sessionMap[state.currSessionId].unread > 0) {
    //     store.dispatch('resetSessionUnread', state.currSessionId)
    // }
    // let count = 0;
    // topic.onData = () => {
    //     ++count;
    //     if (count === 1) {
    //         topic.messages(function (m) {
    //             console.log('msg---->', m)
    //             msgs.push(m)
    //         })
    //     }
    //     return
    // }
    // console.log(msgs)
    // console.log('367----------------------', msgs.length, count)
    // commit('updateCurrSessionMsgs', {
    //     type: 'concat',
    //     msgs: msgs
    // })
    // topic.getMessagesPage(config.localMsglimit).then(() => {
    //     return true
    // }).then(boolea => {
    //     if (boolea) {
    //         // alert(boolea)
    //         topic.messages(function (m) {
    //             console.log('msg---->', m)
    //             msgs.push(m)
    //         })
    //         commit('updateCurrSessionMsgs', {
    //             type: 'concat',
    //             msgs: msgs
    //         })
    //     }
    // }).catch((err) => {
    //     console.log('358--err-->', err.message)
    //     // this.setState({ fetchingMessages: false });
    //     // this.props.onError(err.message, 'err');
    // }).finally(() => {
    //     // topic.messages()
    //     // setTimeout(() => {

    //     // }, 1000)
    // });
    // topic.messages()
    // if (nim) {
    //     let { scene, to } = obj
    //     let options = {
    //         scene,
    //         to,
    //         reverse: false,
    //         asc: true,
    //         limit: config.localMsglimit || 20,
    //         done: function getHistoryMsgsDone(error, obj) {
    //             console.log('309', obj)
    //             if (obj.msgs) {
    //                 if (obj.msgs.length === 0) {
    //                     commit('setNoMoreHistoryMsgs')
    //                 } else {
    //                     let msgs = obj.msgs.map(msg => {
    //                         return formatMsg(msg)
    //                     })
    //                     commit('updateCurrSessionMsgs', {
    //                         type: 'concat',
    //                         msgs: msgs
    //                     })
    //                 }
    //             }
    //             if (error) {
    //                 store.commit('updateCurrSessionId', {
    //                     type: 'destroy'
    //                 })
    //                 Message.error(error.message)
    //                 // alert(error.message)
    //                 console.log(error)
    //             }
    //             store.dispatch('hideLoading')
    //         }
    //     }
    //     if (state.currSessionLastMsg) {
    //         options = Object.assign(options, {
    //             lastMsgId: state.currSessionLastMsg.idServer,
    //             endTime: state.currSessionLastMsg.time,
    //         })
    //     }
    //     store.dispatch('showLoading')
    //     console.log(options)
    // const topic = nim.getTopic(state.currSessionId);
    // topic.getMessagesPage(options)
    // }
}

// 获取本地消息
// export function getL

export function resetNoMoreHistoryMsgs({ commit }) {
    commit('resetNoMoreHistoryMsgs')
}

// 继续与机器人会话交互
export function continueRobotMsg({ commit }, robotAccid) {
    commit('continueRobotMsg', robotAccid)
}
